﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetcodeTest._100._10
{
    public class Leetcode6
    {
        public void Test()
        {
            try
            {
                //题目不能理解，答案错误。！！！！
                Convert("abcd", 2);
            }
            catch (Exception ex)
            { }
        }

        /*
         6. ZigZag Conversion 

             The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 
             */
        public string Convert(string s, int numRows)
        {
            if (numRows < 2)
                return s;
            List<string> list = new List<string>();
            for (int i = 0; i < s.Length; )
            {
                if (s.Length > (i + numRows+1))
                    list.Add(s.Substring(i, numRows + 1));
                else
                    list.Add(s.Substring(i));
                i = i + numRows + 1;
            }
            string retS = "";

            int outputPosition = numRows / 2;
            if (numRows % 2 == 0)
            {
                outputPosition--;
            }

            bool hasOutput = false;
            for (int i = 0; i < numRows; i++)
            {
                foreach (var a in list)
                {
                    if (a.Length > i && (!hasOutput || i != a.Length - 1))
                        retS += a[i];
                    if (i == outputPosition && i < a.Length - 1)
                    {                        
                        retS += a[a.Length - 1];
                    }
                }

                if (i == outputPosition)
                {
                    hasOutput = true;
                }
            }
            return retS;
        }
    }
}
